###################################################################################

library(data.table)
library(tableone) 
library(argparser)

##############################################################################

argp <- arg_parser("Compare Base line")
argp <- add_argument(argp, "--input_file", help="")
argp <- add_argument(argp, "--out_dir", help="Output path")

argv <- parse_args(argp)

input_file <- argv$input_file
out_dir <- argv$out_dir

if(1!=1){

    input_file <- "/public/home/xxf2019/20220915_gastric_multiple/dna_combinePublic/public_ref/combine/MutationInfo.combine.addMolecularSubType.rmMIX.addsurv.tsv"
    out_dir <-"/public/home/xxf2019/20220915_gastric_multiple/dna_combinePublic/public_ref/combine/"

}

dir.create(out_dir , recursive = T)

###################################################################################

dat_base <- data.frame(fread(input_file , header = T))

###################################################################################
######## 生成基线表
## 三类
dat <- dat_base

myVars <- c("Gender" , "Age" , "Tobacco" , "Alcohol" , "Stage" , "HP" , "Class" , "Molecular.subtype" , "OS_status" , "OS_month")
factorVars <- c("Gender" , "Tobacco" , "Alcohol" , "Stage" , "HP", "Class" , "Molecular.subtype" , "OS_status")

dat$Gender <- factor(dat$Gender , level = c("female" , "male" , "unknown") )
dat$Tobacco <- factor(dat$Tobacco , level = c("Smoke" , "No" , "unknown") )
dat$Alcohol <- factor(dat$Alcohol , level = c("Drink" , "No" , "unknown") )
dat$HP <- factor(dat$HP , level = c("Positive" , "Negative" , "unknown") )
dat$Stage <- factor(dat$Stage , level = c("I" , "II" , "III" , "IV" , "unknown") )
#dat$From <- factor(dat$From , level = c("NJMU" , "EastAsian" , "HK" , "TCGA" ) )
dat$From <- factor(dat$From , level = c("NJMU" , "OncoSG" , "TCGA" , "TMUCIH" , "Utokyo" ) )
dat$Age <- as.numeric(dat$Age)
dat$Molecular.subtype <- factor(dat$Molecular.subtype , level = c("MSI" , "POLE" , "EBV" , "CIN" , "GS" , "CIN|GS" , "unknown") )
dat$OS_month <- as.numeric(dat$OS_month)

for(from in unique(dat$From)){
    print(from)
    tmp_dat <- subset( dat , From == from & OS_status !="unknown" )
    print(quantile(tmp_dat$OS_month))
}

tab <- CreateTableOne(vars = myVars,  
               data = dat , 
               strata = 'From',
               factorVars = factorVars,
               includeNA = TRUE)
tab <- print(tab, showAllLevels = TRUE, 
    quote = FALSE, # 不显示引号
    noSpaces = TRUE, # 删除用于在R控制台中对齐文本的空格
    catDigits = 2, contDigits = 2, pDigits = 2, # 修改连续变量小数位数为2位,分类变量百分比位数为2位,调整小数位数为2位；
    printToggle = FALSE)

out_file <- paste(out_dir , "/STAD-CombinePublic.BaseLineCompare.csv",sep="")
write.csv(tab , out_file  )